/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.model.codes;

import org.zhiqim.kernel.util.Hexs;

/**
 * 十六进制加解密算法，默认定义KEY值
 * 
 * @version v1.0.0 @author zouzhigang 2014-2-27 新建与整理
 */
public class HEX
{
    private static String KEY = "!@#$%^";

    /**
     * 加密,给定一个字符串，通过作^转成16进制方式加密
     * 
     * @param str 加密前字符串
     * @return 加密后字符串
     */
    public static String encrypt(String str)
    {
        return encrypt(str, KEY);
    }
    
    /**
     * 加密,给定一个字符串，通过作^转成16进制方式加密
     * 
     * @param str 加密前字符串
     * @return 加密后字符串
     */
    public static String encrypt(String str, String key)
    {
        int keyLen = key.length();
        StringBuilder strb = new StringBuilder();
        for(int i=0;i<str.length();i++)
        {
            char k = key.charAt(i % keyLen);
            int ch = str.charAt(i)^k;
            String hex = Integer.toHexString(ch);
            if (hex.length() == 1)
                hex = "0" + hex;
            strb.append(hex);
        }   
        
        return strb.toString();
    }
    
    /**
     * 解密,给定一个字符串，通过加密的逆操作进行解密
     * 
     * @param str 解密前字符串
     * @return 解密后字符串
     */
    public static String decrypt(String str)
    {
        return decrypt(str, KEY);
    }
    
    /**
     * 解密,给定一个字符串，通过加密的逆操作进行解密
     * 
     * @param str 解密前字符串
     * @return 解密后字符串
     */
    public static String decrypt(String str, String key)
    {
        if(str.length() %2 != 0) 
            str = "0" + str;   
        
        int keyLen = key.length();
        StringBuilder strb = new StringBuilder();
        for(int i=0;i<str.length();i+=2)
        {
            char k = key.charAt((i/2) % keyLen);
            int b = Hexs.hexToByte(str.charAt(i + 1));     
            b = (b + 0x10 * Hexs.hexToByte(str.charAt(i)));
            b = b ^ k;
            strb.append((char)b);
        }
        return strb.toString();
    }
}
